/**
 * 处理包含id upid的数组 返回树形数据
 * @export [] 返回序列化后的树形数组
 * @param { array } list 获取到的数组
 * @param { string } idName id名字
 * @param { string } upIdName 父级id名
 */
export default function parseList(list, idName, upIdName) {
  console.log(list)
  if (list.length > 0) {
    // _.uniqBy(list, idName)
    let map = {}
    let topid = findUpId(list)
    list.forEach((item) => {
      if (!map[item[idName]]) {
        map[item[idName]] = item
      }
    })
    list.forEach((item) => {
      if (item[upIdName] !== topid) {
        // map[item[upIdName]].children ? map[item[upIdName]].children.push(item) : (map[item[upIdName]].children = [item])
        if (map[item[upIdName]]) {
          if (map[item[upIdName]].children) {
            map[item[upIdName]].children.push(item)
          } else {
            (map[item[upIdName]].children = [item])
          }
        }
      }
    })
    let ret = list.filter((item) => {
      return item[upIdName] === topid
    })
    addIsLeaf(ret, 0)
    return ret
  } else {
    return []
  }
  function findUpId(arr) {
    let upId = arr[0][upIdName]
    for (let item of arr) {
      let id = item[idName]
      for (let item2 of arr) {
        if (item2[idName] !== id && upId === item2[idName]) {
          upId = item2[upIdName]
        }
      }
    }
    return upId
  }
  function addIsLeaf(list, num) {
    let curNum = num
    for (let item of list) {
      item.isLeaf = curNum + 1
      if (item.children && item.children.length) {
        addIsLeaf(item.children, curNum + 1)
      }
    }
  }
}
